package com.springboot.controller;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.springboot.bean.Code;
import com.springboot.entity.*;
import com.springboot.util.*;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;
import com.springboot.biz.ItemBiz;
import com.springboot.biz.OperatorBiz;
import com.springboot.biz.PipeBiz;
import com.springboot.biz.ProjectBiz;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@RestController
@RequestMapping(value = "/project")
public class ProjectController {

    @Value(value = "${mypath}")
    private String path;
    @Value("${myfile}")
    private String myfile;

    @Resource
    private HelperPDF helperPDF;

    @Resource
    private TranHelper tranHelper;
    @Resource
    private ModeHelper modeHelper;
    @Resource
    private ModePreview modePreview;
    @Resource
    private OperatorBiz operatorBiz;
    @Resource
    private ProjectBiz projectBiz;
    @Resource
    private PipeBiz pipeBiz;
    @Resource
    private ItemBiz itemBiz;

    private Map<String, Object> map = null;
    private List<String> names = null;

    /**
     * 获取个人项目列表
     */
    @RequestMapping(value = "/showlist")
    public ModelAndView showList(String name, String sort, @RequestParam(defaultValue = "1") int page) {
        ModelAndView view = new ModelAndView("project/showlist");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "未提交", "sort", sort, "page", page, "user", user);
        if (!StringUtils.isEmpty(name))
            map.put("name", name);
        PageInfo<Project> info = projectBiz.findViewProject(map);
        view.addObject("projects", info.getList());
        view.addObject("count", info.getPages());
        view.addObject("page", page);
        return view;
    }

    /**
     * 获取公司项目列表
     */
    @RequestMapping(value = "/findlist")
    public ModelAndView findList(String name, String sort, @RequestParam(defaultValue = "1") int page) {
        ModelAndView view = new ModelAndView("project/findlist");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "已提交", "sort", sort, "page", page, "company", user.getCompany());
        if (!StringUtils.isEmpty(name))
            map.put("name", name);
        PageInfo<Project> info = projectBiz.findViewProject(map);
        view.addObject("projects", info.getList());
        view.addObject("count", info.getPages());
        view.addObject("page", page);
        return view;
    }

    @RequestMapping(value = "/sitelist")
    public ModelAndView siteList(String name, String sort, @RequestParam(defaultValue = "1") int page) {
        ModelAndView view = new ModelAndView("project/sitelist");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "待完成", "commit", "N", "sort", sort, "page", page, "company", user.getCompany());
        if (!StringUtils.isEmpty(name))
            map.put("name", name);
        PageInfo<Project> info = projectBiz.findViewProject(map);
        view.addObject("projects", info.getList());
        view.addObject("count", info.getPages());
        view.addObject("page", page);
        return view;
    }

    @RequestMapping(value = "/sitepost", method = RequestMethod.POST)
    public ModelAndView sitePost(String name, String sort, @RequestParam(defaultValue = "1") int page) {
        ModelAndView view = new ModelAndView("project/sitepost");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "待完成", "commit", "Y", "sort", sort, "page", page, "company", user.getCompany());
        if (!StringUtils.isEmpty(name))
            map.put("name", name);
        PageInfo<Project> info = projectBiz.findViewProject(map);
        view.addObject("projects", info.getList());
        view.addObject("count", info.getPages());
        view.addObject("page", page);
        return view;
    }

    @RequestMapping(value = "/viewlist1", method = RequestMethod.POST)
    public List<Project> viewList1(String name, @RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "未提交", "real", name, "user", user);
        return projectBiz.findListProject(map).getList().stream().filter(project -> project.getId() != id)
                .collect(Collectors.toList());
    }

    @RequestMapping(value = "/viewlist2", method = RequestMethod.POST)
    public List<Project> viewList2(String name, @RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "已提交", "real", name, "company", user.getCompany());
        return projectBiz.findListProject(map).getList().stream().filter(project -> project.getId() != id)
                .collect(Collectors.toList());
    }

    @RequestMapping(value = "/viewlist3", method = RequestMethod.POST)
    public List<Project> viewList3(String name, @RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "待完成", "commit", "N", "real", name, "company", user.getCompany());
        return projectBiz.findListProject(map).getList().stream().filter(project -> project.getId() != id)
                .collect(Collectors.toList());
    }

    @RequestMapping(value = "/viewlist4", method = RequestMethod.POST)
    public List<Project> viewList4(String name, @RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "待完成", "commit", "Y", "real", name, "company", user.getCompany());
        return projectBiz.findListProject(map).getList().stream().filter(project -> project.getId() != id)
                .collect(Collectors.toList());
    }

    /**
     * 根据井号编号查询管道
     *
     * @return
     */
    @RequestMapping(value = "/iquerylist")
    public ModelAndView querylist(String name, @RequestParam(defaultValue = "1") int page) {
        ModelAndView view = new ModelAndView("project/iquerylist");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "未提交", "page", page, "size", 15, "user", user);
        if (!StringUtils.isEmpty(name))
            map.put("name", name);
        PageInfo<Pipe> info = projectBiz.queryListPipe(map);
        view.addObject("pipes", info.getList());
        view.addObject("count", info.getPages());
        view.addObject("page", page);
        return view;
    }

    /**
     * 根据井号编号查询管道
     *
     * @return
     */
//    @RequestMapping(value = "/querylists")
//    public ModelAndView querylists(String name, @RequestParam(defaultValue = "1") int page) {
//        ModelAndView view = new ModelAndView("project/querylists");
//        User user = (User) AppHelper.findMap("user");
//        map = AppHelper.getMap("state", "已提交", "page", page, "company", user.getCompany());
//        if (!StringUtils.isEmpty(name))
//            map.put("name", name);
//        PageInfo<Pipe> info = projectBiz.queryListPipe(map);
//        view.addObject("pipes", info.getList());
//        view.addObject("count", info.getPages());
//        view.addObject("page", page);
//        return view;
//    }
    @RequestMapping(value = "querylists", method = RequestMethod.GET)
    public ModelAndView querylists() {
        return new ModelAndView("project/querylists");
    }

    @RequestMapping(value = "/getmanholes", method = RequestMethod.POST)
    public PageInfo<Pipe> getManholes(String name, @RequestParam(defaultValue = "0") int companyID, @RequestParam(defaultValue = "1") int page) {
        map = AppHelper.getMap("state", "已提交", "page", page, "size", 10, "companyid", companyID);
        if (!StringUtils.isEmpty(name))
            map.put("name", name);
        return projectBiz.queryListPipe(map);
    }


    /**
     * 新建项目信息
     */
    @RequestMapping(value = "/insertview")
    public ModelAndView insertView() {
        ModelAndView view = new ModelAndView("project/insert");
        User user = (User) AppHelper.findMap("user");
        names = operatorBiz.findListName(user.getCompany());
        view.addObject("names", names);
        return view;
    }

    /**
     * 新建项目
     */
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public ModelAndView insert(Project project) {
        ModelAndView view = new ModelAndView();
        User user = (User) AppHelper.findMap("user");
        project.setState("未提交");
        project.setUser(user);
        int id = projectBiz.appendProject(project);
        view.setViewName("redirect:editinfo?id=" + id);
        return view;
    }

    /**
     * 更新项目信息
     */
    @RequestMapping(value = "/updateview")
    public ModelAndView updateView(@RequestParam(defaultValue = "0") int id) {
        ModelAndView view = new ModelAndView("userview/failure");
        User user = (User) AppHelper.findMap("user");
        Project project = projectBiz.findInfoProject(id, user);
        if (StringUtils.isEmpty(project))
            return view;
        names = operatorBiz.findListName(user.getCompany());
        view.setViewName("project/update");
        view.addObject("project", project);
        view.addObject("names", names);
        return view;
    }

    /**
     * 更新项目
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ModelAndView update(Project project) {
        ModelAndView view = new ModelAndView("userview/failure");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", project.getId(), "user", user);
        if (projectBiz.findInfoProject(map) == null)
            return view;
        projectBiz.updateProject(project);
        view.setViewName("redirect:/success");
        return view;
    }

    @RequestMapping(value = "/replacview")
    public ModelAndView replacView(@RequestParam(defaultValue = "0") int id) {
        ModelAndView view = new ModelAndView("userview/failure");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", id, "company", user.getCompany());
        Project project = projectBiz.findInfoProject(map);
        if (StringUtils.isEmpty(project))
            return view;
        names = operatorBiz.findListName(user.getCompany());
        view.setViewName("project/replac");
        view.addObject("project", project);
        view.addObject("names", names);
        return view;
    }

    @RequestMapping(value = "/replac", method = RequestMethod.POST)
    public ModelAndView replac(Project project) {
        ModelAndView view = new ModelAndView("userview/failure");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", project.getId(), "company", user.getCompany());
        if (projectBiz.findInfoProject(map) == null)
            return view;
        projectBiz.updateProject(project);
        view.setViewName("redirect:/success");
        return view;
    }

    /**
     * 提交数据
     */
    @RequestMapping(value = "/submit")
    public boolean submit(@RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        Project project = projectBiz.findInfoProject(id, user);
        if (!StringUtils.isEmpty(project)) {
            project.setState("已提交");
            projectBiz.updateProject(project);
        }
        return true;
    }

    /**
     * 撤回项目
     */
    @RequestMapping(value = "/revoke")
    public boolean revoke(@RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", id, "company", user.getCompany());
        Project project = projectBiz.findInfoProject(map);
        if (!StringUtils.isEmpty(project)) {
            project.setState("未提交");
            projectBiz.updateProject(project);
        }
        return true;
    }

    /**
     * 删除项目
     */
    @RequestMapping(value = "/delete")
    public boolean delete(@RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        Project project = projectBiz.findInfoProject(id, user);
        if (!StringUtils.isEmpty(project))
            projectBiz.deleteProject(project);
        return true;
    }

    /**
     * 移除项目
     */
    @RequestMapping(value = "/remove")
    public boolean remove(@RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", id, "company", user.getCompany());
        Project project = projectBiz.findInfoProject(map);
        if (!StringUtils.isEmpty(project))
            projectBiz.deleteProject(project);
        return true;
    }

    /**
     * 提交数据
     */
    @RequestMapping(value = "/sitework/submit")
    public boolean siteworkSubmit(@RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", id, "company", user.getCompany());
        Project project = projectBiz.findInfoProject(map);
        if (!StringUtils.isEmpty(project)) {
            project.setCommit("Y");
            projectBiz.updateProject(project);
            // 复制当前项目
            project.setState("未提交");
            project.setCommit(null);
            project.setMaster(project.getId() + "");
            projectBiz.insertProject(project);
            for (Pipe pipe : pipeBiz.findListPipe(project)) {
                pipe.setProject(project);
                pipeBiz.insertPipe(pipe);
                for (Item item : itemBiz.findListItem(pipe)) {
                    item.setPipe(pipe);
                    itemBiz.insertItem(item);
                }
            }
        }
        return true;
    }

    /**
     * 移除项目
     */
    @RequestMapping(value = "/sitework/remove")
    public boolean siteworkRemove(@RequestParam(defaultValue = "0") int id) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", id, "company", user.getCompany());
        Project project = projectBiz.findInfoProject(map);
        if (!StringUtils.isEmpty(project))
            projectBiz.deleteProject(project);
        return true;
    }


    /**
     * 获取项目列表
     */
    @RequestMapping(value = "/combinelist")
    public List<Project> combineList(String name) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "已提交", "company", user.getCompany());
        if (!StringUtils.isEmpty(name))
            map.put("name", name);
        PageInfo<Project> info = projectBiz.findListProject(map);
        return info.getList();
    }

    /**
     * 合并项目
     */
    @RequestMapping(value = "/combine", method = RequestMethod.POST)
    public ModelAndView combine(String list) {
        ModelAndView view = new ModelAndView("project/comview");
        User user = (User) AppHelper.findMap("user");
        List<Project> projects = projectBiz.combinProject(list, user.getCompany());
        view.addObject("projects", projects);
        view.addObject("list", list);
        return view;
    }

    /**
     * 合并项目
     */
    @RequestMapping(value = "/comview", method = RequestMethod.GET)
    public ModelAndView comview() {
        return new ModelAndView("project/comview");
    }

    /**
     * 合并项目
     */
    @RequestMapping(value = "/compipe", method = RequestMethod.POST)
    public ModelAndView comPipe(String[] id, String[] no, String[] master) {
        ModelAndView view = new ModelAndView("userview/success");
        if (id.length != master.length || no.length != master.length) {
            view.setViewName("userview/failure");
            return view;
        }
        for (int i = 0; i < id.length; i++) {
            Pipe pipe = pipeBiz.findInfoPipe(Convert.toInt(id[i]), null);
            if (Objects.isNull(pipe))
                continue;
            pipe.setNo(Convert.toInt(no[i]));
            Project project = new Project();
            project.setId(Convert.toInt(master[i]));
            pipe.setProject(project);
            pipeBiz.updatePipe(pipe);
        }
        for (String value : master) {
            Project project = new Project();
            project.setId(Convert.toInt(value));
            itemBiz.sortItemImages(project);
        }
        return view;
    }


    /**
     * 编辑项目
     */
    @RequestMapping(value = "/editinfo")
    public ModelAndView editInfo(int id, @RequestParam(defaultValue = "0") int no) {
        ModelAndView view = new ModelAndView("userview/failure");
        User user = (User) AppHelper.findMap("user");
        Project project = projectBiz.findInfoProject(id, user);
        if (StringUtils.isEmpty(project))
            return view;
        view.setViewName("project/editinfo");
        Pipe pipe = new Pipe();
        List<Pipe> pipes = pipeBiz.findListPipe(project);
        if (pipes != null && pipes.size() != 0) {
            no = no >= pipes.size() ? pipes.size() - 1 : no;
            pipe = pipes.get(no);
            pipe.setItems(itemBiz.findListItem(pipe));
        }
        names = operatorBiz.findListName(user.getCompany());
        List<Code> codes = CodeHelper.findList();
        view.addObject("project", project);
        view.addObject("pipes", pipes);
        view.addObject("names", names);
        view.addObject("codes", codes);
        view.addObject("pipe", pipe);
        view.addObject("path", path);
        return view;
    }

    /**
     * 项目浏览
     */
    @RequestMapping(value = "/findinfo")
    public ModelAndView findInfo(int id, @RequestParam(defaultValue = "0") int no) {
        ModelAndView view = new ModelAndView("userview/failure");
        Project project = projectBiz.findInfoProject(id, null);
        if (StringUtils.isEmpty(project))
            return view;
        view.setViewName("project/findinfo");
        Pipe pipe = new Pipe();
        List<Pipe> pipes = pipeBiz.findListPipe(project);
        if (pipes != null && pipes.size() != 0) {
            no = no >= pipes.size() ? pipes.size() - 1 : no;
            pipe = pipes.get(no);
            pipe.setItems(itemBiz.findListItem(pipe));
        }
        view.addObject("project", project);
        view.addObject("pipes", pipes);
        view.addObject("pipe", pipe);
        view.addObject("path", path);
        return view;
    }

    @RequestMapping(value = "/checkview")
    public ModelAndView check(int id, @RequestParam(defaultValue = "0") int no) {
        ModelAndView view = new ModelAndView("userview/failure");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", id, "company", user.getCompany());
        Project project = projectBiz.findInfoProject(map);
        if (StringUtils.isEmpty(project))
            return view;
        Pipe pipe = new Pipe();
        List<Pipe> pipes = pipeBiz.findListPipe(project);
        if (pipes != null && pipes.size() != 0) {
            no = no >= pipes.size() ? pipes.size() - 1 : no;
            pipe = pipes.get(no);
            pipe.setItems(itemBiz.findListItem(pipe));
        }
        names = operatorBiz.findListName(user.getCompany());
        List<Code> codes = CodeHelper.findList();
        view.setViewName("project/checkview");
        view.addObject("project", project);
        view.addObject("pipes", pipes);
        view.addObject("names", names);
        view.addObject("codes", codes);
        view.addObject("pipe", pipe);
        view.addObject("path", path);
        return view;
    }

    /**
     * 编辑项目
     */
    @RequestMapping(value = "/sitework/editinfo")
    public ModelAndView siteworkEditInfo(int id, @RequestParam(defaultValue = "0") int no) {
        ModelAndView view = new ModelAndView("userview/failure");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", id, "company", user.getCompany());
        Project project = projectBiz.findInfoProject(map);
        if (StringUtils.isEmpty(project))
            return view;
        view.setViewName("project/siteinfo");
        Pipe pipe = new Pipe();
        List<Pipe> pipes = pipeBiz.findListPipe(project);
        if (pipes != null && pipes.size() != 0) {
            no = no >= pipes.size() ? pipes.size() - 1 : no;
            pipe = pipes.get(no);
            pipe.setItems(itemBiz.findListItem(pipe));
        }
        names = operatorBiz.findListName(user.getCompany());
        List<Code> codes = CodeHelper.findList();
        view.addObject("project", project);
        view.addObject("pipes", pipes);
        view.addObject("names", names);
        view.addObject("codes", codes);
        view.addObject("pipe", pipe);
        view.addObject("path", path);
        return view;
    }

    /**
     * 导入项目
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public ModelAndView inportItems(MultipartFile file) {
        ModelAndView view = new ModelAndView();
        User user = (User) AppHelper.findMap("user");
        view.setViewName("redirect:showlist");
        if (!StringUtils.isEmpty(file))
            modeHelper.ItemMode(file, user);
        return view;
    }

    /**
     * 导入深度
     */
    @RequestMapping(value = "/importdepth", method = RequestMethod.POST)
    public ModelAndView importDepth(int id, MultipartFile xfile) {
        ModelAndView view = new ModelAndView("userview/failure");
        User user = (User) AppHelper.findMap("user");
        Project project = projectBiz.findInfoProject(id, user);
        if (project == null || xfile == null)
            return view;
        view.setViewName("redirect:editinfo?id=" + id);
        projectBiz.importProject(project, xfile);
        return view;
    }

    /**
     * 预览文件
     */
    @RequestMapping(value = "/preview")
    public ModelAndView previewItem(MultipartFile file) {
        ModelAndView view = new ModelAndView("userview/failure");
        String name = modePreview.ItemMode(file);
        if (StringUtils.isEmpty(name))
            return view;
        String local = path.replace("ItemImage", "TempFile");
        view.setViewName("redirect:" + local + name + ".pdf");
        return view;
    }

    @Transactional
    @RequestMapping(value = "/convert")
    public ModelAndView convertItem(MultipartFile[] files) {
        ModelAndView view = new ModelAndView("redirect:showlist");
        ConvertUtils convertUtils = new ConvertUtils();
        Project project = convertUtils.initProject(files);
        if (project == null)
            return view;
//        List<Pipe> pipes = project.getPipes();
//        pipes.forEach(pipe -> Computes.computePipe(pipe, project.getStandard()));
//
//        String path = myfile + "/TempFile/" + project.getName();
//        helperPDF.initPDF(project, path + ".PDF");
//        File file = FileUtil.file(path + ".PDF");
//        InputStream stream = new FileInputStream(file);
//
//        response.setHeader("Content-disposition", "attachment;filename=" + project.getName() + ".PDF");
//        response.setContentType("application/octet-stream");
//
//        int len;
//        byte[] bytes = new byte[1024];
//        while ((len = stream.read(bytes)) != -1) {
//            response.getOutputStream().write(bytes, 0, len);
//        }
//        stream.close();
        User user = (User) AppHelper.findMap("user");
        project.setClient(user.getCompany().getName());
        project.setOperator("");
        project.setDate(AppHelper.getDate(null));
        project.setUser(user);
        projectBiz.insertProject(project);
        for (Pipe pipe : project.getPipes()) {
            pipeBiz.insertPipe(pipe);
            for (Item item : pipe.getItems()) {
                itemBiz.insertItem(item);
            }
        }
        return view;
    }


    @RequestMapping(value = "/tranview")
    public ModelAndView transView(String name, @RequestParam(defaultValue = "1") int page) {
        ModelAndView view = new ModelAndView("project/tranview");
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("state", "已提交", "page", page, "company", user.getCompany());
        if (!StringUtils.isEmpty(name))
            map.put("name", name);
        PageInfo<Project> info = projectBiz.findListProject(map);
        view.addObject("projects", info.getList());
        view.addObject("count", info.getPages());
        view.addObject("page", page);
        return view;

    }

    /**
     * 转换项目规范
     */
    @RequestMapping(value = "/transitem", method = RequestMethod.POST)
    public boolean trans(@RequestParam(defaultValue = "0") int id, String standard) {
        User user = (User) AppHelper.findMap("user");
        map = AppHelper.getMap("id", id, "company", user.getCompany());
        Project project = projectBiz.findInfoProject(map);
        if (!StringUtils.isEmpty(project))
            tranHelper.convert(project, standard);
        return true;
    }

    @RequestMapping(value = "/export/pipe")
    public void export(int id, HttpServletResponse response) {
        Project project = projectBiz.findInfoProject(id, null);
        if (StringUtils.isEmpty(project))
            return;
        ExcelWriter workbook = ExcelUtil.getWriter(true);
        workbook.setColumnWidth(0, 8);
        workbook.setColumnWidth(1, 12);
        workbook.setColumnWidth(2, 15);
        workbook.setColumnWidth(3, 12);
        workbook.setColumnWidth(4, 10);
        workbook.setColumnWidth(5, 10);
        workbook.setColumnWidth(6, 10);
        workbook.setColumnWidth(7, 18);
        workbook.setDefaultRowHeight(18);

        workbook.addHeaderAlias("item", "Item");
        workbook.addHeaderAlias("date", "Survey Date");
        workbook.addHeaderAlias("location", "Location");
        workbook.addHeaderAlias("section", "Section");
        workbook.addHeaderAlias("material", "Material");
        workbook.addHeaderAlias("type", "Type");
        workbook.addHeaderAlias("size", "Dia (mm)");
        workbook.addHeaderAlias("length", "Surveyed Length (m)");

        List<Pipe> pipes = pipeBiz.findListPipe(project);
        pipes = pipes.stream().peek(pipe -> {
            if (pipe.getSmanholeno() == null)
                pipe.setSmanholeno("");
            if (pipe.getFmanholeno() == null)
                pipe.setFmanholeno("");
            if (!StringUtils.isEmpty(pipe.getDire()))
                pipe.setDire(pipe.getDire() + "S");
            else
                pipe.setDire("");
        }).collect(Collectors.toList());

        List<Map<String, String>> list = new ArrayList<>(pipes.size());
        for (Pipe pipe : pipes) {
            Map<String, String> map = new HashMap<>();
            map.put("item", pipe.getNo() + "");
            map.put("date", pipe.getDate());
            map.put("location", pipe.getRoadname());
            map.put("section", pipe.getSmanholeno() + " " + pipe.getDire() + " " + pipe.getFmanholeno());
            map.put("material", CameHelper.getCameText(pipe.getMater(), "mat"));
            map.put("type", CameHelper.getCameText(pipe.getUses(), "use"));
            map.put("size", pipe.getHsize());
            map.put("length", pipe.getTestlength() + "");
            list.add(map);
        }

        workbook.write(list);
        String name = project.getName() + "_" + project.getDate() + "_Data.xlsx";
        response.setContentType("application/octet-stream;");
        response.setHeader("Content-disposition", "attachment;filename=" + name);
        try {
            workbook.flush(response.getOutputStream());
            response.flushBuffer();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/export/xls")
    public void exportXLS(@RequestParam(defaultValue = "0") int id) {
        Project project = projectBiz.findInfoProject(id, null);
        if (StringUtils.isEmpty(project))
            return;
        List<Pipe> pipes = pipeBiz.findListPipe(project);
        if (pipes == null || pipes.isEmpty())
            return;
        pipes = pipes.stream().peek(pipe -> {
            if ("U".equals(pipe.getDire())) {
                String smh = pipe.getSmanholeno();
                String fmh = pipe.getFmanholeno();
                pipe.setSmanholeno(fmh);
                pipe.setFmanholeno(smh);
            }
            pipe.setItems(itemBiz.findListItem(pipe));
            if (pipe.getItems() != null && !pipe.getItems().isEmpty()) {
                if (pipe.getItems().stream().map(Item::getCode).anyMatch(value -> value.contains("SA") || value.contains("#4")))
                    pipe.setDefine("Y");
                else
                    pipe.setDefine("N");
            }
            Computes.computePipe(pipe, project.getStandard());
            pipe.setSgrade((int) (pipe.getGrade()[0]));
            pipe.setIgrade((int) (pipe.getGrade()[3]));
        }).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>(8);
        map.put("contract", pipes.get(0).getWorkorder());
        map.put("name", project.getName());
        map.put("location", pipes.get(0).getDistrict2());
        map.put("list", pipes);
        try {
            File file = ResourceUtils.getFile("classpath:Template.xlsx");
            TemplateExportParams params = new TemplateExportParams(file.getPath());
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            HttpServletResponse response = AppHelper.getResponse();
            String name = project.getName() + "_" + project.getDate() + "_DSD_Data_.xlsx";
            response.setHeader("Content-disposition", "attachment;filename=" + name);
            response.setContentType("application/octet-stream");
            workbook.write(response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/export/pdf")
    public void exportPDF(HttpServletResponse response, @RequestParam(defaultValue = "0") int id) {
        Project project = projectBiz.findInfoProject(id, null);
        if (StringUtils.isEmpty(project))
            return;
        List<Pipe> pipes = pipeBiz.findListPipe(project);
        List<Pipe> collect = pipes.stream().peek(pipe -> pipe.setItems(itemBiz.findListItem(pipe)))
                .collect(Collectors.toList());
        project.setPipes(collect);

        String filename = project.getName() + "_" + project.getDate();
        response.setHeader("Content-disposition", "attachment;filename=" + filename + ".PDF");
        response.setContentType("application/octet-stream");
        try {
            AppExport appExport = new AppExport();
            byte[] bytes = appExport.initFile(project).toByteArray();
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
